<template>
    <div class="search-div">
        <!-- 搜索表单 -->
        <el-form label-width="70px" size="small">
            <el-form-item label="角色名称">
                <el-input v-model="sysRoleDto.roleName" style="width: 100%" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="fetchData">
                    搜索
                </el-button>
                <el-button size="small" @click="reset">重置</el-button>
            </el-row>
        </el-form>

        <!-- 添加按钮 -->
        <div class="tools-div">
            <el-button type="success" size="small" @click="addShow">添 加</el-button>
        </div>

        <!--- 角色表格数据 -->
        <el-table :data="list" style="width: 100%">
            <el-table-column prop="roleName" label="角色名称" width="180" />
            <el-table-column prop="roleCode" label="角色code" width="180" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" align="center" width="280" #default="scope">
                <el-button type="primary" size="small" @click="editData(scope.row)">
                    修改
                </el-button>
                <el-button type="danger" size="small" @click="deleteData(scope.row.id)">
                    删除
                </el-button>
                <el-button type="warning" size="small" @click="showAssignMenu(scope.row)">
                    分配菜单
                </el-button>
            </el-table-column>
        </el-table>

        <!--分页条-->
        <el-pagination v-model:current-page="pageParams.pageNum" v-model:page-size="pageParams.pageSize"
            :page-sizes="[2, 5, 10, 20]" layout="total, sizes, prev, pager, next" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    </div>


    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改角色" width="30%">
        <el-form label-width="120px">
            <el-form-item label="角色名称">
                <el-input v-model="sysRoleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色Code">
                <el-input v-model="sysRoleForm.roleCode"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input v-model="sysRoleForm.description"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <!-- 分配菜单的对话框 
    // tree组件添加ref属性，后期方便进行tree组件对象的获取
    -->
    <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
        <el-form label-width="80px">
            <el-tree
                    :data="sysMenuTreeList"
                    ref="tree"   
                    show-checkbox
                    default-expand-all
                    :check-on-click-node="true"
                    node-key="id"
                    :props="defaultProps"
            />
            <el-form-item>
                <el-button type="primary" @click="doAssign">提交</el-button>
                <el-button @click="dialogMenuVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>



</template>








<script setup>
// 导入区域
import { ref, onMounted } from 'vue';
import { FindByPage, Save, GetById,Update,DeleteById,GetSysRoleMenuIds,DoAssignMenuIdToSysRole } from '@/api/sysRole'

import { ElMessage, ElMessageBox } from 'element-plus'


//--------------------------------------------------------

// 变量区域

// 分页条总记录数
let total = ref(0)

// 定义表格数据模型
// let list = ref([
//     {"id":9 ,  "roleName": "系统管理员" , "roleCode":"xtgly","createTime": '2023-07-31'},
//     {"id":10 , "roleName": "商品管理员" , "roleCode":"spgly","createTime": '2023-07-31'}
// ])
let list = ref([])

const pageParams = ref({
    pageNum: 1,
    pageSize: 2
})

const sysRoleDto = ref({
    roleName: ''
})

const dialogVisible = ref(false)

const sysRoleForm = ref({
    id:'',
    roleName: '',
    roleCode: '',
    description: ''
})


const dialogMenuVisible = ref(false)

const sysMenuTreeList = ref([])

const tree = ref(null)

const defaultProps = {
    children : 'children',
    label: 'title'
}

let sysRole = {}  //分配菜单时，将角色行数据存储在这个变量上

//--------------------------------------------------------

//函数区域
onMounted(() => {
    fetchData()
})

const fetchData = async () => {
    const { code, message, data } = await FindByPage(pageParams.value.pageNum, pageParams.value.pageSize, sysRoleDto.value)
    total.value = data.total
    list.value = data.list
}

const reset = () => {
    sysRoleDto.value.roleName = ''
    fetchData()
}


const handleSizeChange = (number) => {
    pageParams.value.pageSize = number
    fetchData()
}
const handleCurrentChange = (number) => {
    pageParams.value.pageNum = number
    fetchData()
}


const addShow = () => {
    dialogVisible.value = true
}

const submit = async () => {

    if(sysRoleForm.value.id==''){
        const { message, code } = await Save(sysRoleForm.value)
        if (code == 200) {
            ElMessage.success(message)
            dialogVisible.value = false
            fetchData()
        }
    }else{
        const { message, code } = await Update(sysRoleForm.value)
        if (code == 200) {
            ElMessage.success(message)
            dialogVisible.value = false
            fetchData()
        }
    }


}


const editData = async (row) => {
    //sysRoleForm.value = row  //回显方式一: 直接使用表格数据行进行回显   存在一定问题
    const { data } = await GetById(row.id)
    sysRoleForm.value = data // 回显方式二: 从数据库重新查询最新数据
    dialogVisible.value = true
}


const deleteData = (id)=>{
    ElMessageBox.confirm('您确定要删除这个数据吗?','提示',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async ()=>{ // 确认  事件处理
        const { code,message } = await DeleteById(id);
        ElMessage.success(message)
        fetchData()
    }).catch((e)=>{ // 取消/异常  事件处理    
        if('cancel'==e){ // 取消
            ElMessage.success('用户取消删除')
        }else{
            ElMessage.success('删除操作失败')
        }
    })
    

}


const showAssignMenu = async (row)=>{
    sysRole = row
    dialogMenuVisible.value = true
    const {code,message,data} = await GetSysRoleMenuIds(row.id)
    sysMenuTreeList.value = data.sysMenuList
    tree.value.setCheckedKeys(data.roleMenuIds)   // 进行数据回显
}

const doAssign = async()=>{

    const checkecNodes = tree.value.getCheckedNodes(); //获取树上勾选的节点数组
    const checkedMenuList = checkecNodes.map(item => {
        return {
            menuId: item.id,
            isHalf: 0
        }
    })


    const isHalfCheckecNodes = tree.value.getHalfCheckedNodes(); //获取树上半勾选的节点数组
    const isHalfCheckedMenuList = isHalfCheckecNodes.map(item => {
        return {
            menuId: item.id,
            isHalf: 1
        }
    })

    //将两个数组合并成一个数组
    const allMenuList = [...checkedMenuList,...isHalfCheckedMenuList]
    console.log(allMenuList)

    const dto = {
        roleId: sysRole.id,
        menuIdList: allMenuList
    }

    const {code,message} = await DoAssignMenuIdToSysRole(dto)
    if(code==200){
        ElMessage.success(message)
        dialogMenuVisible.value = false
    }
    

}





</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}
</style>